package com.szsfm.vehiclemanagement.fragment;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.orhanobut.logger.Logger;
import com.szsfm.vehiclemanagement.R;
import com.szsfm.vehiclemanagement.activity.CameraActivity;
import com.szsfm.vehiclemanagement.activity.MainActivity;
import com.szsfm.vehiclemanagement.base.BaseFragment;
import com.szsfm.vehiclemanagement.bean.Latlng;
import com.szsfm.vehiclemanagement.constant.Config;
import com.szsfm.vehiclemanagement.event.CommEvent;
import com.szsfm.vehiclemanagement.http.http.HttpManager;
import com.szsfm.vehiclemanagement.http.http.HttpResponse;
import com.szsfm.vehiclemanagement.http.http.HttpResponseCallback;
import com.szsfm.vehiclemanagement.http.okhttp.OkhttpManager;
import com.szsfm.vehiclemanagement.mvp.presenter.LocationPresenter;
import com.szsfm.vehiclemanagement.mvp.view.ILocationView;
import com.szsfm.vehiclemanagement.tcp.TcpCore;
import com.szsfm.vehiclemanagement.util.BitmapUtil;
import com.szsfm.vehiclemanagement.util.DateUtil;
import com.szsfm.vehiclemanagement.util.ToastUtil;
import com.szsfm.vehiclemanagement.view.CustomDatePicker;
import com.szsfm.vehiclemanagement.view.MScrollView;
import com.szsfm.vehiclemanagement.view.RulesDialog;
import com.szsfm.vehiclemanagement.view.VehicleImageGroup;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Created by zhoubigbo on 2017/11/8.
 */
public class HomeFragment extends BaseFragment implements View.OnClickListener, MainActivity.OnActivityResultListener, Config, ILocationView {

    Button mSubmitButton;
    MScrollView mScrollView;
    EditText mPlateEditText;
    Activity mContext;
    TextView mLocationTextView;
    TextView mTimeTextView;
    CustomDatePicker mDatePicker;
    TextView ruleTypeTextView;
    VehicleImageGroup mImageGroup;
    LocationPresenter locationPresenter;
    Button mPrintButton;
    Latlng mLatlng = new Latlng();
    String mTime;
    int mType;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View selfView = inflater.inflate(R.layout.fragment_home, container, false);
        Logger.d("this =" + this);
        mContext = getActivity();
        mPlateEditText = selfView.findViewById(R.id.plate_no_edt);
        mLocationTextView = selfView.findViewById(R.id.location_text);
        mTimeTextView = selfView.findViewById(R.id.time_picker_text);
        ruleTypeTextView = selfView.findViewById(R.id.rule_type_text);
        mImageGroup = selfView.findViewById(R.id.vehicle_img_group);
        ruleTypeTextView.setOnClickListener(this);
        mTimeTextView.setOnClickListener(this);
        mLocationTextView.setOnClickListener(this);
        mImageGroup.addButton.setOnClickListener(this);
        mSubmitButton = selfView.findViewById(R.id.submit_button);
        mSubmitButton.setOnClickListener(this);
        mScrollView = selfView.findViewById(R.id.scroll_view);
        locationPresenter = new LocationPresenter(this, mContext.getApplicationContext());
        locationPresenter.startLocation();
        mPrintButton = selfView.findViewById(R.id.print_button);
        mPrintButton.setOnClickListener(this);
        mDatePicker = new CustomDatePicker(mContext, resultHandler, "2017-12-22 00:00", DateUtil.fomate("yyyy-MM-dd HH:mm"));
        String fmt = String.format("违章类型:" + RulesDialog.items[0]);
        ruleTypeTextView.setText(fmt);
        return selfView;
    }


    @Override
    public void startLocation() {
        ToastUtil.show("正在定位");
    }

    @Override
    public void locationResult(Latlng latlng) {
        ToastUtil.show("定位成功:" + latlng.getLatitue() + "," + latlng.getLongitue());
        String fmt = String.format("当前位置:%s", latlng.getPlace());
        mLocationTextView.setText(fmt);
        mLatlng.setLatitue(latlng.getLatitue());
        mLatlng.setLongitue(latlng.getLongitue());
    }


    @Override
    public void onClick(View view) {
        if (view == mSubmitButton) {
            upload();
        } else if (view == mTimeTextView) {
            String now = DateUtil.fomate("yyyy-MM-dd HH:mm");
            mDatePicker.show(now);
        } else if (view == mLocationTextView) {
            locationPresenter.startLocation();
        } else if (view == ruleTypeTextView) {
            RulesDialog.show(getActivity(), dialogItemClickListener);
        } else if (view == mImageGroup.addButton) {
            if (mImageGroup.imgSize == 4) {
                Toast.makeText(mContext, "不能添加更多", Toast.LENGTH_LONG).show();
                return;
            }
            Intent intent = new Intent();
            intent.setClass(mContext, CameraActivity.class);
            startActivityForResult(intent, 6);
            //ImageCapture.startCapture(mContext);
        } else if (view == mPrintButton) {
            ToastUtil.show("请先上传执法信息");
        }
    }

    DialogInterface.OnClickListener dialogItemClickListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            String fmt = String.format("违章类型:" + RulesDialog.items[which]);
            ruleTypeTextView.setText(fmt);
            mType = which;
        }
    };

    CustomDatePicker.ResultHandler resultHandler = new CustomDatePicker.ResultHandler() {
        @Override
        public void handle(Date time) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
            String fmtTime = "时间:" + sdf.format(time);
            mTimeTextView.setText(fmtTime);
            sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);
            mTime = sdf.format(time);
        }
    };

    //上传违章信息
    private void upload() {
        String plate = mPlateEditText.getText().toString();
        if (TextUtils.isEmpty(plate)) {
            ToastUtil.show("车牌号不能为空");
            return;
        }

        if (TextUtils.isEmpty(mTime)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);
            Date time  =mDatePicker.getTime();
            mTime = sdf.format(time);
        }
        String[] filenames = new String[]{mTime + "1" + ".jpg", mTime + "2" + ".jpg", mTime + "3" + ".jpg"};
        TcpCore.updateVehicleInfo(plate, mLatlng.getLatitue(), mLatlng.getLongitue(), mTime, mType, filenames);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCreateVIEvent(CommEvent ev) {
        if (ev.type == CommEvent.EVENT_TYPE_CREATE_VI) {
            if (ev.ret == 0) {
               List<File> lst=mImageGroup.getImageFiles();
               if (!lst.isEmpty()){
                   for (int i=0;i<lst.size();i++){
                       File b = lst.get(i);
                       String filename = mTime+i+".jpg";
                       uploadImages(i+1,b,filename);
                   }
               }
            }
        }
    }

    private void uploadImages(final int index,File b,String filename){
        String plate = mPlateEditText.getText().toString();
        HttpManager manager = new OkhttpManager();
        manager.uploadImages("http://sm.szsfm.com/API/UploadFile.ashx", b, filename, plate, new HttpResponseCallback() {
            @Override
            public void onCallback(HttpResponse success) {
               ToastUtil.show("图片上传成功:"+index+"张");
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data, String path) {
        Uri uri = imageUriFromActivityResult(data,path);
        if (uri != null) {
            mImageGroup.addImage(uri);
        }
    }

    private Uri imageUriFromActivityResult(Intent data, String path){
        if (data != null) {
            if (data.hasExtra("Path")){
                String sdPath = data.getStringExtra("Path");
                mImageGroup.addImage(sdPath);
                return null;
            }
            Uri uri = data.getData();
            if (uri == null) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return null;
                }
                Bitmap bitmap = (Bitmap) bundle.get("data");
                if (bitmap == null) {
                    if (!TextUtils.isEmpty(path)) {
                        bitmap = BitmapUtil.getBitmapByPath(path);
                    }
                }
                if (bitmap == null) {
                    return null;
                }
                return Uri.parse(MediaStore.Images.Media.insertImage(mContext.getContentResolver(), bitmap, null, null));
            }
        }
        return null;
    }

    @Override
    public void onPlateNoResult(String CarNumber) {
        mPlateEditText.setText(CarNumber);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    class OnCam implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setClass(mContext, CameraActivity.class);
            startActivityForResult(intent, 6);
        }
    }

}
